package com.guomao.utils;

import java.util.HashMap;
import java.util.Map;

public class JwtExample {
    
    public static void main(String[] args) {
        System.out.println("=== JJWT 使用示例 ===");
        
        // 示例 1: 生成简单的 JWT
        System.out.println("\n1. 生成简单的 JWT:");
        String simpleToken = JwtUtils.generateSimpleToken("user123");
        System.out.println("简单 JWT: " + simpleToken);
        
        // 示例 2: 生成包含自定义声明的 JWT
        System.out.println("\n2. 生成包含自定义声明的 JWT:");
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", 12345);
        claims.put("role", "ADMIN");
        claims.put("email", "user@example.com");
        claims.put("department", "IT");
        
        String fullToken = JwtUtils.generateToken("user123", claims);
        System.out.println("完整 JWT: " + fullToken);
        
        // 示例 3: 解析 JWT
        System.out.println("\n3. 解析 JWT:");
        try {
            io.jsonwebtoken.Claims parsedClaims = JwtUtils.parseToken(fullToken);
            System.out.println("主题: " + parsedClaims.getSubject());
            System.out.println("用户ID: " + parsedClaims.get("userId"));
            System.out.println("角色: " + parsedClaims.get("role"));
            System.out.println("邮箱: " + parsedClaims.get("email"));
            System.out.println("签发时间: " + parsedClaims.getIssuedAt());
            System.out.println("过期时间: " + parsedClaims.getExpiration());
        } catch (Exception e) {
            System.out.println("解析失败: " + e.getMessage());
        }
        
        // 示例 4: 验证 JWT
        System.out.println("\n4. 验证 JWT:");
        boolean isValid = JwtUtils.validateToken(fullToken);
        System.out.println("JWT 是否有效: " + isValid);
        
        // 示例 5: 获取特定声明
        System.out.println("\n5. 获取特定声明:");
        String subject = JwtUtils.getSubjectFromToken(fullToken);
        Object role = JwtUtils.getClaimFromToken(fullToken, "role");
        System.out.println("主题: " + subject);
        System.out.println("角色: " + role);
        
        // 示例 6: 检查令牌是否即将过期
        System.out.println("\n6. 检查令牌过期状态:");
        boolean isExpiringSoon = JwtUtils.isTokenExpiringSoon(fullToken, 3600000); // 1小时内过期
        System.out.println("令牌是否即将过期: " + isExpiringSoon);
        
        // 示例 7: 刷新令牌
        System.out.println("\n7. 刷新令牌:");
        String refreshedToken = JwtUtils.refreshToken(fullToken);
        System.out.println("刷新后的令牌: " + refreshedToken);
        
        // 示例 8: 验证刷新后的令牌
        System.out.println("\n8. 验证刷新后的令牌:");
        boolean isRefreshedValid = JwtUtils.validateToken(refreshedToken);
        System.out.println("刷新后的令牌是否有效: " + isRefreshedValid);
        
        // 示例 9: 处理无效令牌
        System.out.println("\n9. 处理无效令牌:");
        String invalidToken = "invalid.token.here";
        boolean isInvalidValid = JwtUtils.validateToken(invalidToken);
        System.out.println("无效令牌验证结果: " + isInvalidValid);
    }
}